package com.hzit.loan.pay.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.payment.wap.models.AlipayTradeWapPayResponse;
import com.hzit.loan.pay.commonApi.resp.PayResultData;
import com.hzit.loan.pay.commonApi.resp.RespVo;
import com.hzit.loan.pay.commonApi.utils.PayDigestUtil;
import com.hzit.loan.pay.config.PayConfig;
import com.hzit.loan.pay.mapper.MchInfoMapper;
import com.hzit.loan.pay.model.MchInfo;
import com.hzit.loan.pay.model.PaySerial;
import com.hzit.loan.pay.service.IPayStrategyService;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

@Service
public class AlipayWapPayImpl implements IPayStrategyService, InitializingBean {

    @Autowired
    private PayConfig payConfig;

    @Autowired
    private MchInfoMapper mchInfoMapper;


    private Logger logger = LoggerFactory.getLogger(AlipayWapPayImpl.class);


    @Override
    public RespVo<PayResultData> pay(PaySerial paySerial) {

        //设置系统参数
        Config config = new Config();
        config.protocol = "https";
        config.gatewayHost = "openapi.alipaydev.com";
        config.signType = "RSA2";

        config.appId = payConfig.getAlipayAppId();

        config.merchantPrivateKey = payConfig.getPrivateKey();

        config.alipayPublicKey = payConfig.getAliapyPubKey();
        config.notifyUrl = "http://127.0.0.1:8822/payNotify/recive";

        Factory.setOptions(config);


        try {

            //TODO
            //return_url: 支付成功自动跳转的页面  可不传
            //quitUrl： 支付中断跳转的页面 必传
            //notify_url： 支付成功后异步跳转的地址，后端通知，主要用来更新，交易状态 可不传

            AlipayTradeWapPayResponse response =  Factory.Payment.Wap().pay(paySerial.getSubject(),
                    paySerial.getPaySerialNo(),paySerial.getMchOrderAmount().toString(),
                    paySerial.getQuitUrl(),paySerial.getReturnUrl());

            String url = response.getBody();
            if(StringUtils.isEmpty(url)){
                logger.info("支付流水号{}:调用支付宝接口失败：返回body为空",paySerial.getPaySerialNo());
                return RespVo.getFailReturn("调用支付宝接口失败");
            }

            PayResultData payResultData = new PayResultData();
            payResultData.setMchId(paySerial.getMchId());
            payResultData.setMchOrderId(paySerial.getMchOrderNo());
            payResultData.setPayChannel(paySerial.getPayChannel());
            payResultData.setPayWay(payResultData.getPayWay());
            payResultData.setPayUrl(response.getBody());
            //返回参数签名

            RespVo respVo = new RespVo();
            MchInfo mchInfo = mchInfoMapper.queryMchInfoByMchId(paySerial.getMchId());
            Map map = JSONObject.parseObject(JSONObject.toJSONString(payResultData), Map.class);
            String sign = PayDigestUtil.getSign(map,mchInfo.getRespKey(),"sign");
            payResultData.setSign(sign);
            respVo.setData(payResultData);
            return respVo;
        } catch (Exception e) {
            logger.error("Exception",e);
            return RespVo.getFailReturn(e.getMessage());
        }

    }

    @Override
    public void afterPropertiesSet() throws Exception {

    }
}

